#include "logger.h"
#include <QDebug>
#include <QDateTime>

// 禁止其他文件访问，只能通过接口设置
static LogMode      g_logMode = LM_FILE;
static QString      g_filePath;
static int          g_port = 8989;
static DatabaseInfo g_dbInfo;

void setLogMode(LogMode mode)
{
    g_logMode = mode;
}

void setLogFilePath(const QString &path)
{
    g_filePath = path;
}

void setLogNetPort(int port)
{
    g_port = port;
}

void setLogDatabaseInfo(const DatabaseInfo &info)
{
    g_dbInfo = info;
}

void log(QtMsgType type, const QMessageLogContext &info, const QString &msg)
{
    QString lType;
    switch (type) {
    case QtDebugMsg:
        lType = "Debug";
        break;
    case QtInfoMsg:
        lType = "Info";
        break;
    case QtWarningMsg:
        lType = "Warning";
        break;
    case QtCriticalMsg:
        lType = "Critical";
        break;
    case QtFatalMsg:
        lType = "Faltal";
        break;
    default:
        break;
    }
    static Logger       g_logger;
    g_logger.outputLog(lType, info.file, info.function, info.line, msg);
}


Logger::Logger(QObject *parent)
    : QObject(parent)
{
    setOutputMode(g_logMode);
}

Logger::~Logger()
{
    qInstallMessageHandler(Q_NULLPTR);
    if(m_db.isOpen())
        m_db.close();
}

void Logger::setOutputMode(LogMode mode)
{
    if(LM_DATABASE == mode) {
        if(m_db.isOpen())
            m_db.close();
        m_db = QSqlDatabase::addDatabase("QMYSQL");
        m_db.setHostName(g_dbInfo.server);
        m_db.setUserName(g_dbInfo.user);
        m_db.setPassword(g_dbInfo.passwd);
        m_db.setPort(g_dbInfo.port);
        m_db.setDatabaseName(g_dbInfo.dbName);
        m_db.open();
    }
}

void Logger::outputLog(const QString &type, const char* file, const char* func, int line, const QString &msg)
{
    QMutexLocker locker(&m_mutex);
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString str = QString("[%1] [%2] [%3] [%4] [line:%5] ===> %6\n")
            .arg(type).arg(file).arg(func).arg(time).arg(line).arg(msg);
    if(LM_FILE == g_logMode) {
        QString name = QString("%1/%2.txt").arg(g_filePath).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
        QDir dir(g_filePath);
        if(!dir.exists())
            dir.mkpath(g_filePath);
        QFile           m_file(name);
        if(!m_file.open(QIODevice::WriteOnly | QIODevice::Append))
            return;
        m_file.write(str.toUtf8());
        m_file.close();
    }
    else if(LM_NET == g_logMode) {
        m_socket.writeDatagram(str.toUtf8(), QHostAddress::Broadcast, g_port);
    }
    else if(LM_DATABASE == g_logMode) {
        try {
            QString sql = QString("insert into log values('%1', '%2', '%3', '%4', '%5', '%6');")
                    .arg(time).arg(type).arg(file).arg(func).arg(line).arg(msg);
            QSqlQuery query(m_db);
            query.exec(sql);
        }
        catch (const QSqlError &e) {
            e.text();
        }
    }
}
